$(document).ready(function() {
  $("form").delegate(".component", "mousedown", function(md) {
    $(".popover").remove();

    md.preventDefault();
    var tops = [];
    var mouseX = md.pageX;
    var mouseY = md.pageY;
    var $temp;
    var $this = $(this);
    var delays = {
      main: 0,
      form: 120
    }
    var type;

    if ($this.parent().parent().parent().parent().attr("id") === "components") {
      type = "main";
    } else {
      type = "form";
    }

    var delayed = setTimeout(function() {
      if (type === "main") {
        $temp = $("<form class='form-horizontal span6' id='temp'></form>").append($this.clone());
      } else {
        if ($this.attr("id") !== "legend") {
          $temp = $("<form class='form-horizontal span6' id='temp'></form>").append($this);
        }
      }

      $("body").append($temp);

      $temp.css({
        "position": "absolute",
        "top": mouseY - ($temp.height() / 2) + "px",
        "left": mouseX - ($temp.width() / 2) + "px",
        "opacity": "0.9"
      }).show()

      var half_box_height = ($temp.height() / 2);
      var half_box_width = ($temp.width() / 2);
      var $target = $("#target");
      var tar_pos = $target.offset();
      var $target_component = $("#target .component");

      $(document).delegate("body", "mousemove", function(mm) {

        var mm_mouseX = mm.pageX;
        var mm_mouseY = mm.pageY;

        $temp.css({
          "top": mm_mouseY - half_box_height + "px",
          "left": mm_mouseX - half_box_width + "px"
        });
        $target_component.css({
          "border-top": "1px solid white",
          "border-bottom": "none"
        });

        if (mm_mouseX > tar_pos.left &&
          mm_mouseX < tar_pos.left + $target.width() + $temp.width() / 2 &&
          mm_mouseY > tar_pos.top &&
          mm_mouseY < tar_pos.top + $target.height() + $temp.height() / 2
        ) {
          $target.css("background-color", "#fafdff");
          tops = $.grep($target_component, function(e) {
            return ($(e).offset().top - mm_mouseY + half_box_height > 0 && $(e).attr("id") !== "legend");
          });
          if (tops.length > 0) {
            $(tops[0]).css("border-top", "1px solid #22aaff");
          } else {
            if ($target_component.length > 0) {
              $($target_component[$target_component.length - 1]).css("border-bottom", "1px solid #22aaff");
            }
          }
        } else {
          $target.css("background-color", "#fff");
        }
      });

      $("body").delegate("#temp", "mouseup", function(mu) {
        mu.preventDefault();

        var mu_mouseX = mu.pageX;
        var mu_mouseY = mu.pageY;
        var tar_pos = $target.offset();

        $target_component.css({
          "border-top": "1px solid white",
          "border-bottom": "none"
        });

        // acting only if mouse is in right place
        if (mu_mouseX + half_box_width > tar_pos.left &&
          mu_mouseX - half_box_width < tar_pos.left + $target.width() &&
          mu_mouseY + half_box_height > tar_pos.top &&
          mu_mouseY - half_box_height < tar_pos.top + $target.height()
        ) {
          $temp.attr("style", null);
          // where to add
          if (tops.length > 0) {
            $($temp.html()).insertBefore(tops[0]);
          } else {
            $("#target fieldset").append($temp.append("\n\n\ \ \ \ ").html());
          }
        } else {
          tops = [];
        }

        //clean up & add popover
        $target.css("background-color", "#fff");
        $(document).undelegate("body", "mousemove");
        $("body").undelegate("#temp", "mouseup");
        $("#target .component").popover({
          trigger: "manual"
        });
        $temp.remove();
      });
    }, delays[type]);

    $(document).mouseup(function() {
      clearInterval(delayed);
      return false;
    });
    $(this).mouseout(function() {
      clearInterval(delayed);
      return false;
    });
  });
});